<template>
  <div class="app-container">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-header">
            <span>今日销售额</span>
            <el-tag size="small">{{ compareWithYesterday(overviewData.todaySales) }}</el-tag>
          </div>
          <div class="card-number">¥ {{ overviewData.todaySales }}</div>
          <div class="card-footer">
            昨日：¥ {{ overviewData.yesterdaySales }}
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-header">
            <span>今日订单数</span>
            <el-tag size="small">{{ compareWithYesterday(overviewData.todayOrders) }}</el-tag>
          </div>
          <div class="card-number">{{ overviewData.todayOrders }}</div>
          <div class="card-footer">
            昨日：{{ overviewData.yesterdayOrders }}
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-header">
            <span>今日新增用户</span>
            <el-tag size="small">{{ compareWithYesterday(overviewData.todayUsers) }}</el-tag>
          </div>
          <div class="card-number">{{ overviewData.todayUsers }}</div>
          <div class="card-footer">
            昨日：{{ overviewData.yesterdayUsers }}
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-header">
            <span>转化率</span>
            <el-tag size="small">{{ compareWithYesterday(overviewData.conversionRate) }}</el-tag>
          </div>
          <div class="card-number">{{ overviewData.conversionRate }}%</div>
          <div class="card-footer">
            昨日：{{ overviewData.yesterdayRate }}%
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="16">
        <el-card>
          <div slot="header" class="clearfix">
            <span>销售趋势</span>
            <el-radio-group v-model="salesTimeRange" size="mini" style="float: right">
              <el-radio-button label="week">近7天</el-radio-button>
              <el-radio-button label="month">近30天</el-radio-button>
            </el-radio-group>
          </div>
          <div ref="salesChart" style="height: 350px" />
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card>
          <div slot="header" class="clearfix">
            <span>用户来源分布</span>
          </div>
          <div ref="userSourceChart" style="height: 350px" />
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="12">
        <el-card>
          <div slot="header" class="clearfix">
            <span>商品销量排行</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="handleExport">
              导出数据
            </el-button>
          </div>
          <el-table :data="productRankings" height="400" border>
            <el-table-column label="排名" type="index" width="50" align="center" />
            <el-table-column label="商品名称" prop="name" />
            <el-table-column label="销量" prop="sales" width="100" align="center" />
            <el-table-column label="销售额" width="120" align="center">
              <template slot-scope="{row}">
                ¥ {{ row.amount }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div slot="header" class="clearfix">
            <span>用户行为分析</span>
          </div>
          <div ref="userBehaviorChart" style="height: 400px" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getSalesStats, getUserBehaviorStats, getProductRankings, getUserGrowth, exportStatistics } from '@/api/statistics'
import { parseTime } from '@/utils'

export default {
  name: 'StatisticsDashboard',
  data() {
    return {
      salesTimeRange: 'week',
      overviewData: {
        todaySales: 0,
        yesterdaySales: 0,
        todayOrders: 0,
        yesterdayOrders: 0,
        todayUsers: 0,
        yesterdayUsers: 0,
        conversionRate: 0,
        yesterdayRate: 0
      },
      productRankings: [],
      salesChart: null,
      userSourceChart: null,
      userBehaviorChart: null
    }
  },
  watch: {
    salesTimeRange: {
      handler(val) {
        this.initSalesChart()
      }
    }
  },
  mounted() {
    this.initData()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.salesChart) this.salesChart.dispose()
    if (this.userSourceChart) this.userSourceChart.dispose()
    if (this.userBehaviorChart) this.userBehaviorChart.dispose()
  },
  methods: {
    initData() {
      this.initSalesChart()
      this.initUserSourceChart()
      this.initUserBehaviorChart()
      this.getProductRankings()
    },
    handleResize() {
      if (this.salesChart) this.salesChart.resize()
      if (this.userSourceChart) this.userSourceChart.resize()
      if (this.userBehaviorChart) this.userBehaviorChart.resize()
    },
    compareWithYesterday(today) {
      // 计算同比增长
      const growth = ((today - yesterday) / yesterday * 100).toFixed(2)
      return growth > 0 ? `+${growth}%` : `${growth}%`
    },
    initSalesChart() {
      if (!this.salesChart) {
        this.salesChart = this.$echarts.init(this.$refs.salesChart, 'custom')
      }
      
      getSalesStats({ timeRange: this.salesTimeRange }).then(response => {
        const { dates, sales, orders } = response.data
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: '#999'
              }
            }
          },
          legend: {
            data: ['销售额', '订单量']
          },
          xAxis: {
            type: 'category',
            data: dates,
            axisPointer: {
              type: 'shadow'
            }
          },
          yAxis: [
            {
              type: 'value',
              name: '销售额',
              min: 0,
              axisLabel: {
                formatter: '¥{value}'
              }
            },
            {
              type: 'value',
              name: '订单量',
              min: 0
            }
          ],
          series: [
            {
              name: '销售额',
              type: 'line',
              data: sales,
              smooth: true,
              itemStyle: {
                color: '#409EFF'
              }
            },
            {
              name: '订单量',
              type: 'bar',
              yAxisIndex: 1,
              data: orders,
              itemStyle: {
                color: '#67C23A'
              }
            }
          ]
        }
        this.salesChart.setOption(option)
      })
    },
    initUserSourceChart() {
      if (!this.userSourceChart) {
        this.userSourceChart = this.$echarts.init(this.$refs.userSourceChart, 'custom')
      }

      getUserBehaviorStats({ type: 'source' }).then(response => {
        const { sources } = response.data
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: sources.map(item => item.name)
          },
          series: [
            {
              type: 'pie',
              radius: '65%',
              center: ['60%', '50%'],
              data: sources,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
        this.userSourceChart.setOption(option)
      })
    },
    initUserBehaviorChart() {
      if (!this.userBehaviorChart) {
        this.userBehaviorChart = this.$echarts.init(this.$refs.userBehaviorChart, 'custom')
      }

      getUserBehaviorStats({ type: 'behavior' }).then(response => {
        const { behaviors } = response.data
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          radar: {
            indicator: behaviors.map(item => ({
              name: item.name,
              max: item.max
            }))
          },
          series: [
            {
              type: 'radar',
              data: [
                {
                  value: behaviors.map(item => item.value),
                  name: '用户行为分析',
                  itemStyle: {
                    color: '#F56C6C'
                  },
                  areaStyle: {
                    color: 'rgba(245, 108, 108, 0.2)'
                  }
                }
              ]
            }
          ]
        }
        this.userBehaviorChart.setOption(option)
      })
    },
    getProductRankings() {
      getProductRankings().then(response => {
        this.productRankings = response.data
      })
    },
    handleExport() {
      this.$confirm('是否确认导出所有统计数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        exportStatistics().then(response => {
          const blob = new Blob([response.data])
          const fileName = `统计数据${parseTime(new Date(), '{y}{m}{d}')}.xlsx`
          if ('download' in document.createElement('a')) {
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href)
            document.body.removeChild(elink)
          } else {
            navigator.msSaveBlob(blob, fileName)
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.data-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #606266;
    font-size: 14px;
  }
  .card-number {
    font-size: 24px;
    padding: 10px 0;
    color: #303133;
  }
  .card-footer {
    color: #909399;
    font-size: 12px;
  }
}
</style> 